package cn.itrip.service;

import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.common.MD5;
import cn.itrip.common.RedisAPI;
import cn.itrip.common.UserAgentUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author jie
 * @date 2019/5/7 -9:48
 */
@Service
public class TokenServiceService implements TokenService {

    @Resource
    private RedisAPI redisAPI;

    @Override
    public String genernateToken(String agent, ItripUser user) throws Exception {
        StringBuffer sb = new StringBuffer();
        sb.append("token:");
        if(UserAgentUtil.CheckAgent(agent)){
            sb.append("MOBILE-");
        }else {
            sb.append("PC-");
        }
        sb.append(MD5.getMd5(user.getUserCode(),32)+"-");
        sb.append(user.getId()+"-");
        sb.append(new SimpleDateFormat("yyyyMMddmmss").format(new Date())+"-");
        sb.append(MD5.getMd5(agent,6));
        return  sb.toString();
    }

    @Override
    public void delToken(String token) throws Exception {
        redisAPI.del(token);
    }

    @Override
    public void saveToken(String token, ItripUser user) throws Exception {
        if(token.startsWith("token:PC-")){
            redisAPI.set(token,2*60*60,JSON.toJSONString(user));
        }else {
            redisAPI.set(token,JSON.toJSONString(user));
        }
    }
}
